<template>
  <div class="edit-userInfo-container">
    <van-nav-bar title="个人资料" left-text="返回" fixed left-arrow @click-left="$router.back()" />
    <div class="user-info">
      <!-- 头像 -->
      <van-cell>
        <template #title>
          <span class="custom-title">头像</span>
        </template>
        <template #right-icon>
          <div class="upload-pic" :style="{ 'background-image': `url(${avatar ? 'http://www.dsl2023hcy.love:3004' + avatar : ''})` }">
            <van-uploader :deletable="false" :after-read="afterRead" />
          </div>
        </template>
      </van-cell>
      <!-- 账号 -->
      <van-cell>
        <template #title>
          <span class="custom-title">账号</span>
        </template>
        <template #right-icon>
          <van-field v-model="account" />
        </template>
      </van-cell>
      <!-- 手机号 -->
      <van-cell>
        <template #title>
          <span class="custom-title">手机号</span>
        </template>
        <template #right-icon>
          <van-field v-model="phone" disabled />
        </template>
      </van-cell>
      <!-- 昵称 -->
      <van-cell>
        <template #title>
          <span class="custom-title">昵称</span>
        </template>
        <template #right-icon>
          <van-field v-model="nickName" />
        </template>
      </van-cell>
      <!-- 性别 -->
      <van-cell>
        <template #title>
          <span class="custom-title">性别</span>
        </template>
        <template #right-icon>
          <span @click="selectSex = true">{{ sex }}</span>
          <van-action-sheet v-model="selectSex" title="选择性别" :closeable="false" :actions="actions" @select="onSelect" />
        </template>
      </van-cell>
      <!-- 邮箱 -->
      <van-cell>
        <template #title>
          <span class="custom-title">邮箱</span>
        </template>
        <template #right-icon>
          <van-field v-model="email" />
        </template>
      </van-cell>
      <!-- 出生日期 -->
      <van-cell>
        <template #title>
          <span class="custom-title">出生日期</span>
        </template>
        <template #right-icon>
          <span @click="show = true">{{ birthday }}</span>
          <van-action-sheet v-model="show" :closeable="false">
            <div class="content"><van-datetime-picker v-model="curBirthday" type="date" title="选择年月日" :min-date="minDate" :max-date="maxDate" @cancel="show = false" @confirm="onConfirm" /></div>
          </van-action-sheet>
        </template>
      </van-cell>
    </div>
    <div class="submit">
      <van-button round block type="info" @click="onSubmit">保存</van-button>
    </div>
  </div>
</template>

<script>
import axios from '@/utils/request/request'
import { Notify } from 'vant'
export default {
  name: 'editUserInfo',
  data() {
    return {
      account: '',
      phone: '',
      nickName: '',
      email: '',
      sex: '',
      birthday: '',
      avatar: '',
      show: false,
      selectSex: false,
      maxDate: new Date(),
      minDate: new Date('1900-01-01'),
      actions: [{ name: '男' }, { name: '女' }]
    }
  },
  computed: {
    curBirthday: {
      get() {
        return new Date(this.birthday)
      },
      set() {}
    }
  },
  methods: {
    onSelect(val) {
      this.selectSex = false
      this.sex = val.name
    },
    // 更新用户头像
    async afterRead(file) {
      // 此时可以自行将文件上传至服务器
      let image_url = file.content
      let image_type = file.file.type.split('/')[1]
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.post('/user/update/avatar', { avatar: image_url, type: '.' + image_type })

        if (data.code === 0) {
          this.avatar = data.data.avatar
          this.$toast.success(data.msg)
        } else if (data.code === 403 || data.msg === '身份认证错误') {
          Notify({ type: 'danger', message: data.msg })
          localStorage.removeItem('user_token')
          this.$router.replace('/login')
        } else {
          this.$toast.success(data.msg)
        }
      } catch {
        Notify({
          type: 'danger',
          message: '请求失败！',
          duration: 1000
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 获取用户信息
    async getUserInfo() {
      this.$toast.loading({
        duration: 0,
        message: '加载中...'
      })
      try {
        const data = await axios.get('/user/userinfo')

        if (data.code === 0) {
          this.account = data.data.name
          this.phone = data.data.phone
          this.nickName = data.data.nickname
          this.email = data.data.email
          this.sex = data.data.sex
          this.avatar = data.data.avatar
          const date = new Date(data.data.birthday)
          const year = date.getFullYear()
          const month = date.getMonth() >= 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
          const day = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate()
          this.birthday = `${year}-${month}-${day}`
        } else if (data.code === 403 || data.msg === '身份认证错误') {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({ type: 'danger', message: data.msg, duration: 1000 })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '请求失败！',
          duration: 1000
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 提交用户信息到服务器进行保存
    async onSubmit() {
      // 1. 验证账号,只能包含字母数字组合
      if (this.account === '') return Notify({ type: 'danger', message: '账号不能为空！', duration: 1000 })
      if (!/^[A-Za-z0-9]{1,64}$/.test(this.account)) return Notify({ type: 'danger', message: '账号为长度1-64位的数字字母组合！', duration: 1000 })
      // 2. 验证手机号
      if (this.phone === '') return Notify({ type: 'danger', message: '手机号不能为空！', duration: 1000 })
      if (!/^1[3-9]\d{9}$/.test(this.phone)) return Notify({ type: 'danger', message: '手机号格式错误！', duration: 1000 })
      // 3.验证昵称
      if (this.nickName === '') return Notify({ type: 'danger', message: '昵称不能为空！', duration: 1000 })
      if (this.nickName.length > 64) return Notify({ type: 'danger', message: '昵称长度位1-64位！', duration: 1000 })
      // 4. 验证性别
      if (this.sex === '') return Notify({ type: 'danger', message: '性别不能为空！', duration: 1000 })
      if (['男', '女'].indexOf(this.sex) === -1) return Notify({ type: 'danger', message: '性别必须是男或者女！', duration: 1000 })
      // 5. 验证邮箱
      if (this.email === '') return Notify({ type: 'danger', message: '邮箱不能为空！', duration: 1000 })
      if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(this.email)) return Notify({ type: 'danger', message: '邮箱格式错误！', duration: 1000 })
      // 6. 验证生日
      if (this.birthday === '') return Notify({ type: 'danger', message: '出生日期不能为空！', duration: 1000 })
      if (!/\d{4}-\d{2}-\d{2}/.test(this.birthday)) return Notify({ type: 'danger', message: '出生日期格式为‘yyyy-mm-dd’！', duration: 1000 })
      // 7. 发送请求保存数据
      this.$toast.loading({
        duration: 0,
        message: '加载中...'
      })
      const data = await axios.post('/user/update/userinfo', {
        account: this.account,
        phone: this.phone,
        nickname: this.nickName,
        email: this.email,
        sex: this.sex,
        birthday: this.birthday
      })
      this.$toast.clear()
      if (data.code === 0) {
        Notify({ type: 'success', message: `${data.msg}`, duration: 1000 })
        this.getUserInfo()
      } else if (data.code === 403 || data.msg === '身份认证错误') {
        Notify({ type: 'danger', message: data.msg })
        localStorage.removeItem('user_token')
        this.$router.replace('/login')
      } else {
        Notify({ type: 'danger', message: data.msg })
      }
    },
    // 生日选中处理函数
    onConfirm(date) {
      const year = date.getFullYear()
      const month = date.getMonth() >= 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
      const day = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate()
      this.birthday = `${year}-${month}-${day}`
      this.show = false
    }
  },
  created() {
    this.getUserInfo()
  }
}
</script>

<style lang="less" scoped>
.edit-userInfo-container {
  padding-top: 46px;
  background-color: #f5f5f5;

  .user-info {
    padding: 20px 20px 10px;
    background-color: white;

    .van-cell {
      height: 50px;
      padding: 0;
      align-items: center;
      padding-bottom: 10px;
      justify-content: space-between;

      .van-cell__title,
      .van-field {
        flex: 1;
      }

      ::v-deep .van-field__control {
        text-align: right;
      }

      // 头像上传
      .upload-pic {
        background-repeat: no-repeat;
        background-size: 100% 100%;
        height: 40px;
        background-position: center center;
        border-radius: 999px;

        ::v-deep .van-uploader__upload {
          margin: 0;
          height: 40px;
          width: 40px;
          background: transparent;

          .van-uploader__upload-icon {
            color: transparent;
            background: transparent;
          }
        }
      }
    }
    .user-desc {
      background-color: white;
      font-size: 14px;

      .desc-title {
        line-height: 40px;
        color: #323232;
      }

      .desc-content {
        height: 32px;

        .content {
          width: 100%;
          border: none;
          outline: none;
          padding: 0;
          color: #969799;
        }
      }
    }
  }
  .submit {
    padding: 0 5px;
    margin-top: 80px;

    .van-button--info {
      background-color: #f92946;
      border-color: #f92946;
    }

    .content {
      padding: 16px 16px 0px;
    }
  }
  ::v-deep .van-nav-bar__text,
  ::v-deep .van-nav-bar .van-icon {
    color: #323232;
  }
}
</style>
